<template>
  <el-dialog
    :model-value="props.visible"
    class="task-detail-dialog"
    width="1400px"
    align-center
    :close-on-click-modal="false"
    :before-close="handleClose"
    @update:model-value="(value: boolean) => emit('update:visible', value)"
  >
    <div class="task-detail" v-if="localTask">
      <div class="detail-body">
        <div class="primary-column">
          <div class="detail-header">
            <div class="header-top">
              <span v-if="localTask?.id" class="detail-id">ID {{ localTask.id }}</span>
              <div class="status-tags">
                <el-tag
                  v-if="localTask?.status"
                  :type="getStatusType(localTask.status)"
                  size="small"
                >
                  {{ getStatusText(localTask.status) }}
                </el-tag>
                <el-tag
                  v-if="localTask?.priority"
                  :type="getPriorityType(localTask.priority)"
                  size="small"
                >
                  {{ getPriorityText(localTask.priority) }}
                </el-tag>
                <el-tag v-if="localTask?.task_type" size="small" type="info">
                  {{ getTaskTypeText(localTask.task_type) }}
                </el-tag>
              </div>
            </div>

            <div class="title-section">
              <div class="field-label">
                <span>任务标题</span>
                <span class="required">*</span>
              </div>
              <el-input
                v-model="localTask.title"
                placeholder="请输入任务标题"
                maxlength="200"
                show-word-limit
                size="large"
                class="title-input"
                :class="{ 'field-error': fieldErrors.title }"
                @blur="handleSaveField('title')"
                @input="clearFieldError('title')"
              />
              <div v-if="fieldErrors.title" class="error-message">{{ fieldErrors.title }}</div>
            </div>

            <div class="header-meta">
              <span v-if="localTask.project_id && localTask.project_name" class="project-info">
                项目：<el-link type="primary" :underline="false">{{ localTask.project_name }}</el-link>
              </span>
              <span v-if="localTask.version_id && localTask.version_name" class="version-info">
                版本：<el-link type="primary" :underline="false">{{ localTask.version_name }}</el-link>
              </span>
              <span class="meta-user-item">
                <span class="meta-label">创建人：</span>
                <UserDisplay
                  v-if="localTask.created_by"
                  :user-id="localTask.created_by"
                  :user-name="localTask.creator_name"
                  :show-avatar="true"
                  size="small"
                />
                <span v-else style="color: #909399;">未指定</span>
              </span>
              <span class="meta-user-item">
                <span class="meta-label">负责人：</span>
                <UserDisplay
                  v-if="localTask.assignee_id"
                  :user-id="localTask.assignee_id"
                  :user-name="localTask.assignee_name"
                  :show-avatar="true"
                  size="small"
                />
                <span v-else style="color: #909399;">未分配</span>
              </span>
              <span class="meta-user-item">
                <span class="meta-label">报告人：</span>
                <UserDisplay
                  v-if="localTask.reporter_id"
                  :user-id="localTask.reporter_id"
                  :user-name="localTask.reporter_name"
                  :show-avatar="true"
                  size="small"
                />
                <span v-else style="color: #909399;">未指定</span>
              </span>
              <span v-if="localTask.created_at">创建时间：{{ formatDateTimeDisplay(localTask.created_at) }}</span>
              <span v-if="localTask.updated_at">更新时间：{{ formatDateTimeDisplay(localTask.updated_at) }}</span>
            </div>
          </div>

          <!-- 主要内容区域 - 任务描述 -->
          <section class="section-card content-section">
            <div class="content-header">
              <div class="content-title">任务描述</div>
              <div class="content-actions">
                <template v-if="!editingContent">
                  <el-button
                    size="small"
                    type="primary"
                    @click="editingContent = true"
                  >
                    编辑
                  </el-button>
                </template>
                <template v-else>
                  <el-button
                    size="small"
                    @click="cancelEditContent"
                  >
                    取消
                  </el-button>
                  <el-button
                    size="small"
                    type="primary"
                    :loading="savingContent"
                    @click="saveContent"
                  >
                    保存
                  </el-button>
                </template>
              </div>
            </div>
            <div class="content-scrollable">
              <div v-if="editingContent" class="content-editor">
                <EnhancedRichTextEditor
                  v-model="localTask.description"
                  placeholder="请输入任务描述..."
                  :min-height="400"
                />
              </div>
              <div v-else class="content-display">
                <div v-if="hasContent(localTask.description)" class="content-display-item">
                  <div class="text-content" v-html="localTask.description"></div>
                </div>
                <div v-if="!hasContent(localTask.description)" class="content-empty">
                  <el-empty description="暂无内容" :image-size="100" />
                </div>
              </div>
            </div>
          </section>

          <!-- 第二组页签：动态、评论、附件、关联项等 -->
          <section class="section-card tabs-card">
            <el-tabs v-model="secondaryTab" class="detail-tabs" :key="`secondary-tabs-${visible}-${localTask?.id || ''}`">
              <el-tab-pane label="动态" name="activities">
                <div class="tab-content" v-if="secondaryTab === 'activities'">
                  <ActivityList
                    entity-type="task"
                    :entity-id="localTask.id"
                    :requirement="localTask"
                    :status-options="statusOptions"
                    :priority-options="priorityOptions"
                    :users="users"
                    :key="`activities-${localTask.id}`"
                  />
                </div>
              </el-tab-pane>

              <el-tab-pane label="评论" name="comments">
                <div class="tab-content" v-if="secondaryTab === 'comments'">
                  <CommentList
                    entity-type="task"
                    :entity-id="localTask.id"
                    :users="users"
                    @comment-count-change="handleCommentCountChange"
                    :key="`comments-${localTask.id}`"
                  />
                </div>
              </el-tab-pane>

              <el-tab-pane label="附件" name="attachments">
                <div class="tab-content" v-if="secondaryTab === 'attachments'">
                  <AttachmentManager
                    :attachments="(localTask as any).attachments || []"
                    :upload-handler="handleUploadAttachment"
                    :delete-handler="handleDeleteAttachment"
                    :download-handler="handleDownloadAttachment"
                    :can-delete="true"
                    @upload-success="handleAttachmentMutation"
                    @delete-success="handleAttachmentMutation"
                    :key="`attachments-${localTask.id}`"
                  />
                </div>
              </el-tab-pane>

              <el-tab-pane label="关联项" name="associations">
                <div class="tab-content" v-if="secondaryTab === 'associations'">
                  <TaskAssociationsTab 
                    ref="taskAssociationsTabRef"
                    :task-id="localTask.id"
                    :project-id="localTask.project_id"
                    :version-ids="localTask.version_id ? [localTask.version_id] : []"
                    :key="`associations-${localTask.id}`"
                    @requirement-updated="handleTaskUpdated"
                    @defect-updated="handleTaskUpdated"
                  />
                </div>
              </el-tab-pane>

              <el-tab-pane label="时间跟踪" name="time-tracking">
                <div class="tab-content" v-if="secondaryTab === 'time-tracking'">
                  <div class="other-info">
                    <div class="other-section">
                      <div class="other-title">时间统计</div>
                      <div class="other-row">
                        <span class="other-label">总耗时</span>
                        <span class="other-value">{{ localTask.total_time_spent || 0 }}h</span>
                      </div>
                      <div class="other-row">
                        <span class="other-label">预估工时</span>
                        <span class="other-value">{{ localTask.estimated_hours || 0 }}h</span>
                      </div>
                      <div class="other-row">
                        <span class="other-label">实际工时</span>
                        <span class="other-value">{{ localTask.actual_hours || 0 }}h</span>
                      </div>
                      <div class="other-row">
                        <span class="other-label">进度</span>
                        <span class="other-value">{{ localTask.progress || 0 }}%</span>
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>

              <el-tab-pane label="其他" name="others">
                <div class="tab-content">
                  <div class="other-info">
                    <div class="other-section">
                      <div class="other-title">时间信息</div>
                      <div class="other-row" v-if="localTask.start_date">
                        <span class="other-label">开始时间</span>
                        <span class="other-value">{{ formatDateTimeDisplay(localTask.start_date) }}</span>
                      </div>
                      <div class="other-row" v-if="localTask.due_date">
                        <span class="other-label">截止时间</span>
                        <span class="other-value">{{ formatDateTimeDisplay(localTask.due_date) }}</span>
                      </div>
                      <div class="other-row">
                        <span class="other-label">创建时间</span>
                        <span class="other-value">{{ formatDateTimeDisplay(localTask.created_at) }}</span>
                      </div>
                      <div class="other-row">
                        <span class="other-label">更新时间</span>
                        <span class="other-value">{{ formatDateTimeDisplay(localTask.updated_at) }}</span>
                      </div>
                    </div>

                    <div class="other-section">
                      <div class="other-title">标签</div>
                      <div class="tag-list">
                        <el-tag v-for="tag in localTask.tags || []" :key="tag" size="small" closable @close="handleRemoveTag(tag)">
                          {{ tag }}
                        </el-tag>
                        <el-button size="small" type="text" @click="showAddTagInput = true" v-if="(localTask.tags || []).length < 10">
                          <el-icon><Plus /></el-icon>
                          添加标签
                        </el-button>
                        <el-input
                          v-if="showAddTagInput"
                          v-model="newTag"
                          placeholder="输入标签"
                          size="small"
                          @keyup.enter="handleAddTag"
                          @blur="showAddTagInput = false"
                          ref="tagInputRef"
                        />
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </section>
        </div>

        <aside class="side-column">
          <section class="info-card">
            <div class="info-card-title">基础字段</div>
            <div class="info-form-group" ref="statusFieldRef">
              <label class="info-label">状态 <span class="required">*</span></label>
              <el-select
                :model-value="localTask.status"
                placeholder="请选择状态"
                size="default"
                :class="{ 'field-error': fieldErrors.status }"
                @update:model-value="(value: string) => handleSaveField('status', value)"
                @change="clearFieldError('status')"
              >
                <el-option
                  v-for="option in statusOptions"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </el-select>
              <div v-if="fieldErrors.status" class="error-message">{{ fieldErrors.status }}</div>
            </div>
            <div class="info-form-group">
              <label class="info-label">优先级</label>
              <el-select
                :model-value="localTask.priority"
                placeholder="请选择优先级"
                size="default"
                @update:model-value="(value: string) => handleSaveField('priority', value)"
              >
                <el-option
                  v-for="option in priorityOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </div>
            <div class="info-form-group">
              <label class="info-label">任务类型</label>
              <el-select
                :model-value="localTask.task_type"
                placeholder="请选择类型"
                size="default"
                @update:model-value="(value: string) => handleSaveField('task_type', value)"
              >
                <el-option
                  v-for="option in taskTypeOptions"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </el-select>
            </div>
            <div class="info-form-group" ref="projectIdFieldRef">
              <label class="info-label">所属项目</label>
              <el-select
                :model-value="localTask.project_id"
                placeholder="请选择项目"
                filterable
                size="default"
                :class="{ 'field-error': fieldErrors.project_id }"
                @update:model-value="(value: string) => handleSaveField('project_id', value)"
                @change="clearFieldError('project_id')"
              >
                <el-option
                  v-for="project in projects"
                  :key="project.id"
                  :label="project.name"
                  :value="project.id"
                />
              </el-select>
              <div v-if="fieldErrors.project_id" class="error-message">{{ fieldErrors.project_id }}</div>
            </div>
            <div class="info-form-group">
              <label class="info-label">关联版本</label>
              <el-select
                :model-value="localTask.version_id"
                placeholder="请选择版本"
                filterable
                size="default"
                :loading="loadingVersions"
                :disabled="!localTask.project_id"
                @update:model-value="(value: string | null) => handleSaveField('version_id', value || null)"
              >
                <el-option
                  v-for="version in availableVersionOptions"
                  :key="version.id"
                  :label="version.name"
                  :value="version.id"
                />
              </el-select>
              <div v-if="!localTask.project_id" class="field-hint" style="font-size: 12px; color: #909399; margin-top: 4px;">
                请先选择所属项目
              </div>
            </div>
            <div class="info-form-group">
              <label class="info-label">任务标签</label>
              <el-select
                :model-value="localTask.tags || []"
                multiple
                filterable
                allow-create
                default-first-option
                collapse-tags
                collapse-tags-tooltip
                placeholder="请选择标签或输入新标签"
                size="default"
                @update:model-value="(value: string[]) => handleSaveField('tags', value)"
              >
                <el-option
                  v-for="tag in commonTagOptions"
                  :key="tag"
                  :label="tag"
                  :value="tag"
                />
              </el-select>
            </div>
            <div class="info-form-group">
              <label class="info-label">进度</label>
              <el-slider
                :model-value="localTask.progress || 0"
                :min="0"
                :max="100"
                :step="1"
                show-input
                @change="(value: number | number[]) => handleSaveField('progress', Array.isArray(value) ? value[0] : value)"
              />
            </div>
          </section>

          <section class="info-card">
            <div class="info-card-title">人员</div>
            <div class="info-form-group" ref="reporterIdFieldRef">
              <label class="info-label">报告人 <span class="required">*</span></label>
              <el-select
                :model-value="localTask.reporter_id"
                placeholder="请选择报告人"
                filterable
                clearable
                size="default"
                :loading="loadingData"
                :class="{ 'field-error': fieldErrors.reporter_id }"
                @update:model-value="(value: string | null) => handleSaveField('reporter_id', value ?? '')"
                @change="clearFieldError('reporter_id')"
              >
                <el-option
                  v-for="user in users"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                >
                  <UserDisplay
                    :user-id="user.id"
                    :user-name="user.name"
                    :user-avatar="user.avatar"
                    :show-avatar="true"
                    size="small"
                  />
                </el-option>
              </el-select>
              <div v-if="fieldErrors.reporter_id" class="error-message">{{ fieldErrors.reporter_id }}</div>
            </div>
            <div class="info-form-group">
              <label class="info-label">负责人</label>
              <el-select
                :model-value="localTask.assignee_id"
                placeholder="请选择负责人（可选）"
                filterable
                clearable
                size="default"
                :loading="loadingData"
                @update:model-value="(value: string | null) => handleSaveField('assignee_id', value ?? '')"
              >
                <el-option
                  v-for="user in users"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                >
                  <UserDisplay
                    :user-id="user.id"
                    :user-name="user.name"
                    :user-avatar="user.avatar"
                    :show-avatar="true"
                    size="small"
                  />
                </el-option>
              </el-select>
            </div>
          </section>

          <section class="info-card">
            <div class="info-card-title">时间信息</div>
            <div class="info-form-group">
              <label class="info-label">开始时间</label>
              <el-date-picker
                :model-value="formatDateTimeForPicker(localTask.start_date)"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择开始时间"
                size="default"
                style="width: 100%"
                @update:model-value="(value: string | null) => handleSaveField('start_date', value || null)"
              />
            </div>
            <div class="info-form-group">
              <label class="info-label">截止时间</label>
              <el-date-picker
                :model-value="formatDateTimeForPicker(localTask.due_date)"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择截止时间"
                size="default"
                style="width: 100%"
                @update:model-value="(value: string | null) => handleSaveField('due_date', value || null)"
              />
            </div>
            <div class="info-form-group">
              <label class="info-label">预估工时</label>
              <el-input-number
                :model-value="localTask.estimated_hours || 0"
                :min="0"
                :precision="2"
                :step="0.5"
                placeholder="请输入预估工时"
                size="default"
                style="width: 100%"
                controls-position="right"
                @update:model-value="(value: number | undefined) => handleSaveField('estimated_hours', value ?? 0)"
              />
              <div class="field-hint">单位：小时</div>
            </div>
            <div class="info-form-group">
              <label class="info-label">实际工时</label>
              <el-input-number
                :model-value="localTask.actual_hours || 0"
                :min="0"
                :precision="2"
                :step="0.5"
                placeholder="请输入实际工时"
                size="default"
                style="width: 100%"
                controls-position="right"
                @update:model-value="(value: number | undefined) => handleSaveField('actual_hours', value ?? 0)"
              />
              <div class="field-hint">单位：小时</div>
            </div>
          </section>
        </aside>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed, nextTick } from 'vue'
import { ElMessage, ElInput } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { Task } from '@/types/task'
import { taskAPI } from '@/api/task'
import { ResponseParser } from '@/utils/responseParser'
import CommentList from '@/components/common/CommentList.vue'
import ActivityList from '@/components/common/ActivityList.vue'
import EnhancedRichTextEditor from '@/components/common/EnhancedRichTextEditor.vue'
import AttachmentManager from '@/components/common/AttachmentManager.vue'
import UserDisplay from '@/components/ui/UserDisplay.vue'
import TaskAssociationsTab from '@/components/task/TaskAssociationsTab.vue'
import { uploadTaskAttachment, deleteTaskAttachment, downloadTaskAttachment } from '@/api/tasks'
import { getUsers } from '@/api/users'
import { getProjectList } from '@/api/project'
import { versionAPI } from '@/api/version'
import { useTaskStates } from '@/composables/useTaskStates'
import { useTaskOptions } from '@/composables/useTaskOptions'
import { useTagsStore } from '@/stores/tags'

interface StatusOption {
  value: string
  label: string
}

interface PriorityOption {
  value: string
  label: string
}

interface UserOption {
  id: string
  name: string
  real_name?: string
  avatar?: string
}

interface ProjectOption {
  id: string
  name: string
}

interface VersionOption {
  id: string
  name: string
  project_id?: string
}

// 任务类型选项
const TASK_TYPE_OPTIONS = [
  { value: 'feature', label: '功能' },
  { value: 'bug', label: '缺陷' },
  { value: 'improvement', label: '改进' },
  { value: 'documentation', label: '文档' },
  { value: 'refactor', label: '重构' },
  { value: 'test', label: '测试' },
  { value: 'other', label: '其他' }
]

// Props
const props = withDefaults(defineProps<{
  taskId: string
  visible?: boolean
  statusOptions?: StatusOption[]
  priorityOptions?: PriorityOption[]
  users?: UserOption[]
  projects?: ProjectOption[]
  versionOptions?: VersionOption[]
  commonTags?: string[]
}>(), {
  visible: false
})

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'update:modelValue': [value: boolean]
  'task-updated': [task: Task]
}>()

// Composables
const { statusOptions: taskStatusOptions, loadStates: loadTaskStates } = useTaskStates()
const { priorityOptions: formattedTaskPriorityOptions, loadOptions: loadTaskOptions } = useTaskOptions()

// Data
const localTask = ref<Task | null>(null)
const originalTask = ref<Task | null>(null)
const fieldErrors = reactive<Record<string, string>>({})
const isUpdatingFromProps = ref(false)
const savingFields = reactive<Record<string, boolean>>({})

// Options data
const statusOptions = computed(() => {
  if (props.statusOptions && props.statusOptions.length > 0) {
    return props.statusOptions
  }
  return taskStatusOptions.value.map((state: any) => ({
    value: state.code || state.value,
    label: state.name || state.label
  }))
})

const priorityOptions = computed(() => {
  if (props.priorityOptions && props.priorityOptions.length > 0) {
    return props.priorityOptions
  }
  // 从 useTaskOptions 获取优先级选项
  return formattedTaskPriorityOptions.value
})

const taskTypeOptions = computed(() => TASK_TYPE_OPTIONS)

const users = ref<UserOption[]>(props.users || [])
const projects = ref<ProjectOption[]>(props.projects || [])
const versionOptions = ref<VersionOption[]>(props.versionOptions || [])

// 计算属性 - 可用的版本选项
const availableVersionOptions = computed(() => {
  if (!localTask.value?.project_id) {
    return versionOptions.value
  }
  return versionOptions.value.filter((version: VersionOption) => 
    !version.project_id || version.project_id === localTask.value?.project_id
  )
})

// 标签选项：从标签管理API获取，同时包含任务中已使用的标签
const tagsStore = useTagsStore()
const commonTagOptions = computed(() => {
  const tagSet = new Set<string>()
  // 添加系统标签（从标签管理模块获取）
  tagsStore.tags.forEach(tag => {
    if (tag.module_type === 'task' || !tag.module_type) {
      tagSet.add(tag.name)
    }
  })
  // 添加任务中已使用的标签（作为补充）
  if (localTask.value?.tags) {
    localTask.value.tags.forEach(tag => tagSet.add(tag))
  }
  // 添加 props 传入的标签
  if (props.commonTags) {
    props.commonTags.forEach(tag => tagSet.add(tag))
  }
  return Array.from(tagSet)
})

// Editing states
const editingContent = ref(false)
const savingContent = ref(false)

// Tabs
const secondaryTab = ref('activities')

const showAddTagInput = ref(false)
const newTag = ref('')
const tagInputRef = ref<InstanceType<typeof ElInput> | null>(null)

// Load data
const loadingData = ref(false)
const hasLoadedBaseData = ref(false)
const loadData = async (forceReload = false) => {
  if (loadingData.value) {
    return
  }
  
  if (hasLoadedBaseData.value && !forceReload) {
    if (localTask.value?.project_id) {
      await loadVersionsByProject(localTask.value.project_id)
    }
    return
  }
  
  try {
    loadingData.value = true
    
    // 加载任务选项（状态和优先级）和标签
    await Promise.all([
      loadTaskStates(),
      loadTaskOptions(),
      tagsStore.fetchTags().catch(err => {
        console.warn('加载系统标签失败，将使用任务中的标签:', err)
        return []
      })
    ])

    if ((!props.users || props.users.length === 0) && users.value.length === 0) {
      try {
        const usersResponse = await getUsers({ page: 1, size: 200 })
        const parsedResult = ResponseParser.parseUserListResponse(usersResponse)
        if (parsedResult.items && parsedResult.items.length > 0) {
          users.value = parsedResult.items.map((user: any) => ({
            id: user.id,
            name: user.name || user.username || `用户${user.id}`,
            real_name: user.real_name || user.name || user.username || `用户${user.id}`,
            avatar: user.avatar || user.avatar_url || ''
          }))
        }
      } catch (error) {
        console.error('加载用户列表失败:', error)
        ElMessage.error('加载用户列表失败，请稍后重试')
      }
    } else if (props.users && props.users.length > 0) {
      users.value = props.users
    }

    if (!props.projects || props.projects.length === 0) {
      const projectsResponse = await getProjectList({ page: 1, size: 200 })
      const projectsData = (projectsResponse as any)?.data?.items || (projectsResponse as any)?.items || []
      if (projectsData.length > 0) {
        projects.value = projectsData.map((project: any) => ({
          id: project.id,
          name: project.name
        }))
      }
    }

    if (localTask.value?.project_id) {
      await loadVersionsByProject(localTask.value.project_id)
    }
    
    hasLoadedBaseData.value = true
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loadingData.value = false
  }
}

// 根据项目ID加载版本列表
const loadingVersions = ref(false)
const loadVersionsByProject = async (projectId: string) => {
  if (!projectId || loadingVersions.value) {
    return
  }

  try {
    loadingVersions.value = true
    const response = await versionAPI.getVersions({ 
      project_id: projectId, 
      limit: 200,
      sort_by: 'created_at',
      sort_order: 'desc'
    })
    
    if (response.success && response.data) {
      const versionsData = response.data.items || []
      versionOptions.value = versionsData.map((v: any) => ({
        id: v.id,
        name: v.name || v.version_number || `版本 ${v.id}`,
        project_id: v.project_id || projectId
      }))
    } else {
      versionOptions.value = []
    }
  } catch (error) {
    console.error('加载版本列表失败:', error)
    versionOptions.value = []
  } finally {
    loadingVersions.value = false
  }
}

// Helper functions
const formatDateTimeDisplay = (dateStr?: string) => {
  if (!dateStr) return '未设置'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const formatDateTimeForPicker = (dateStr?: string | null): string | null => {
  if (!dateStr) return null
  
  try {
    if (dateStr.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/)) {
      return dateStr
    }
    
    let date: Date
    if (dateStr.includes('T')) {
      date = new Date(dateStr)
    } else if (dateStr.match(/^\d{4}-\d{2}-\d{2}$/)) {
      date = new Date(dateStr + 'T00:00:00')
    } else {
      date = new Date(dateStr)
    }
    
    if (isNaN(date.getTime())) {
      console.warn('无法解析日期时间:', dateStr)
      return null
    }
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (error) {
    console.error('格式化日期时间失败:', error, dateStr)
    return null
  }
}


const hasContent = (content?: string | null): boolean => {
  if (!content) return false
  const text = content.replace(/<[^>]*>/g, '').trim()
  return text.length > 0
}

// Status handling - 从状态管理系统动态获取
const { getStateByCode } = useTaskStates()
const getStatusType = (status: string) => {
  if (!status) return 'info'
  const state = getStateByCode(status)
  if (state && state.color) {
    // 将颜色转换为 Element Plus 的 tag type
    const colorMap: Record<string, 'primary' | 'success' | 'warning' | 'danger' | 'info'> = {
      '#67C23A': 'success',
      '#E6A23C': 'warning',
      '#F56C6C': 'danger',
      '#409EFF': 'primary',
      '#909399': 'info'
    }
    for (const [color, type] of Object.entries(colorMap)) {
      if (state.color.toLowerCase() === color.toLowerCase()) {
        return type
      }
    }
    // 如果颜色不匹配，根据状态名称判断
    if (state.name.includes('完成') || state.name.includes('已') || state.name.includes('成功')) {
      return 'success'
    }
    if (state.name.includes('进行') || state.name.includes('处理') || state.name.includes('中') || state.name.includes('分配')) {
      return 'warning'
    }
    if (state.name.includes('取消') || state.name.includes('失败') || state.name.includes('拒绝')) {
      return 'danger'
    }
    if (state.name.includes('待') || state.name.includes('新')) {
      return 'info'
    }
  }
  return 'info'
}

const getStatusText = (status: string) => {
  const option = statusOptions.value.find(opt => opt.value === status)
  return option?.label || status
}

const getPriorityType = (priority: string) => {
  const priorityMap: Record<string, 'primary' | 'success' | 'warning' | 'danger' | 'info'> = {
    lowest: 'info',
    low: 'info',
    medium: 'warning',
    high: 'warning',
    urgent: 'danger',
    critical: 'danger'
  }
  return priorityMap[priority] || 'info'
}

const getPriorityText = (priority: string) => {
  const option = priorityOptions.value.find(opt => opt.value === priority)
  return option?.label || priority
}

const getTaskTypeText = (type?: string) => {
  if (!type) return '未知'
  const option = taskTypeOptions.value.find(opt => opt.value === type)
  return option?.label || type
}

// Save handling
const handleSaveField = async (field: keyof Task, value?: any) => {
  if (value !== undefined && localTask.value) {
    ;(localTask.value as any)[field] = value
  }
  if (!localTask.value || !localTask.value.id) return
  if (!originalTask.value) return

  const previous = originalTask.value[field]
  const nextValue = localTask.value[field]

  const isEqual = (a: any, b: any) => {
    if (a === b) return true
    if ((a === null || a === undefined || a === '') && (b === null || b === undefined || b === '')) return true
    if (Array.isArray(a) && Array.isArray(b)) {
      if (a.length !== b.length) return false
      return a.every((val, idx) => val === b[idx])
    }
    return false
  }

  if (isEqual(nextValue, previous)) {
    return
  }

  ;(originalTask.value as any)[field] = nextValue

  if (savingFields[field as string]) {
    return
  }

  savingFields[field as string] = true
  try {
    const updatePayload: any = { [field]: nextValue }
    const response = await taskAPI.updateTask(localTask.value.id, updatePayload)
    const parsed = ResponseParser.parseResponse(response)
    if (!parsed.success) {
      throw new Error(parsed.message || '更新失败')
    }

    ElMessage.success('更新成功')
    emit('task-updated', localTask.value)
  } catch (error) {
    const message = ResponseParser.extractMessage(error) || '更新失败'
    ElMessage.error(message)
    fieldErrors[field as string] = message
  } finally {
    savingFields[field as string] = false
  }
}

const clearFieldError = (field: string) => {
  delete fieldErrors[field]
}

// Content editing
const cancelEditContent = () => {
  editingContent.value = false
  if (localTask.value && originalTask.value) {
    localTask.value.description = originalTask.value.description
  }
}

const saveContent = async () => {
  if (!localTask.value || !localTask.value.id) return
  
  savingContent.value = true
  try {
    const response = await taskAPI.updateTask(localTask.value.id, { 
      description: localTask.value.description 
    })
    const parsed = ResponseParser.parseResponse(response)
    if (!parsed.success) {
      throw new Error(parsed.message || '更新失败')
    }

    if (originalTask.value) {
      originalTask.value.description = localTask.value.description
    }
    editingContent.value = false
    ElMessage.success('保存成功')
    emit('task-updated', localTask.value)
  } catch (error) {
    const message = ResponseParser.extractMessage(error) || '保存失败'
    ElMessage.error(message)
  } finally {
    savingContent.value = false
  }
}

// Tag handling
const handleAddTag = () => {
  if (!localTask.value || !newTag.value.trim() || (localTask.value.tags || []).includes(newTag.value.trim())) {
    showAddTagInput.value = false
    return
  }
  
  const tag = newTag.value.trim()
  if (!localTask.value.tags) {
    localTask.value.tags = []
  }
  localTask.value.tags.push(tag)
  newTag.value = ''
  showAddTagInput.value = false
  handleSaveField('tags')
}

const handleRemoveTag = (tag: string) => {
  if (!localTask.value || !localTask.value.tags) return
  
  const index = localTask.value.tags.indexOf(tag)
  if (index !== -1) {
    localTask.value.tags.splice(index, 1)
    handleSaveField('tags')
  }
}

// Attachment handlers
const handleUploadAttachment = async (file: File) => {
  if (!localTask.value?.id) {
    throw new Error('任务ID不存在')
  }
  try {
    const response = await uploadTaskAttachment(localTask.value.id, file)
    if (response && response.success) {
      await loadTaskDetail()
      ElMessage.success('附件上传成功')
    }
  } catch (error) {
    ElMessage.error('附件上传失败')
    console.error('附件上传失败:', error)
    throw error
  }
}

const handleDeleteAttachment = async (attachment: any) => {
  if (!localTask.value?.id) return
  try {
    await deleteTaskAttachment(localTask.value.id, attachment.id)
    await loadTaskDetail()
    ElMessage.success('附件删除成功')
  } catch (error) {
    ElMessage.error('附件删除失败')
    console.error('附件删除失败:', error)
    throw error
  }
}

const handleDownloadAttachment = async (attachment: any) => {
  if (!localTask.value?.id) return
  try {
    const response = await downloadTaskAttachment(localTask.value.id, attachment.id)
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', attachment.filename || attachment.original_filename || 'attachment')
    document.body.appendChild(link)
    link.click()
    link.remove()
    window.URL.revokeObjectURL(url)
    ElMessage.success('附件下载已开始')
  } catch (error) {
    ElMessage.error('附件下载失败')
    console.error('附件下载失败:', error)
    throw error
  }
}

const handleAttachmentMutation = () => {
  loadTaskDetail()
}

const handleCommentCountChange = () => {
  // Handle comment count change if needed
}

// 任务关联更新处理
const taskAssociationsTabRef = ref<InstanceType<typeof TaskAssociationsTab> | null>(null)
const handleTaskUpdated = async () => {
  // 刷新关联列表
  // 使用 nextTick 确保组件已经完全更新
  await nextTick()
  if (taskAssociationsTabRef.value && secondaryTab.value === 'associations') {
    try {
      // 刷新需求和缺陷列表（关联操作可能影响两者）
      taskAssociationsTabRef.value.refreshRequirements?.()
      taskAssociationsTabRef.value.refreshDefects?.()
    } catch (error) {
      console.error('刷新关联列表失败:', error)
    }
  }
}

// Load task detail
const loadTaskDetail = async () => {
  if (!props.taskId) {
    localTask.value = null
    return
  }

  try {
    const response = await taskAPI.getTask(props.taskId)
    if (response && response.data) {
      isUpdatingFromProps.value = true
      try {
        localTask.value = response.data
        originalTask.value = { ...response.data }
        if (!hasLoadedBaseData.value && !loadingData.value) {
          await loadData()
        }
        if (localTask.value?.project_id) {
          await loadVersionsByProject(localTask.value.project_id)
        }
      } finally {
        isUpdatingFromProps.value = false
      }
    } else {
      ElMessage.error('加载任务详情失败：响应数据为空')
      localTask.value = null
    }
  } catch (error) {
    ElMessage.error('加载任务详情失败')
    console.error('加载任务详情失败:', error)
    localTask.value = null
  }
}

// Watchers
watch(
  () => props.visible,
  (visible, oldVisible) => {
    if (visible) {
      if (!oldVisible && !loadingData.value) {
        loadData()
      }
      if (props.taskId) {
        loadTaskDetail()
      }
    } else {
      secondaryTab.value = 'activities'
      editingContent.value = false
    }
  },
  { immediate: true }
)

watch(
  () => props.taskId,
  (newTaskId) => {
    if (newTaskId && props.visible) {
      loadTaskDetail()
    } else if (!newTaskId) {
      localTask.value = null
      originalTask.value = null
    }
  },
  { immediate: true }
)

watch(
  () => localTask.value?.project_id,
  async (newProjectId, oldProjectId) => {
    if (isUpdatingFromProps.value) {
      return
    }
    
    if (newProjectId && newProjectId !== oldProjectId) {
      await loadVersionsByProject(newProjectId)
    } else if (!newProjectId) {
      versionOptions.value = []
    }
  }
)

watch(
  () => props.users,
  (newUsers) => {
    if (newUsers && newUsers.length > 0) {
      users.value = newUsers
      hasLoadedBaseData.value = true
    }
  },
  { immediate: true, deep: true }
)

watch(
  () => props.projects,
  (newProjects) => {
    if (newProjects && newProjects.length > 0) {
      projects.value = newProjects
    }
  },
  { immediate: true, deep: true }
)

// 监听关联项标签页切换，确保数据加载
watch(
  () => secondaryTab.value,
  async (newTab) => {
    if (newTab === 'associations' && localTask.value?.id) {
      // 当切换到关联项标签页时，等待组件创建后刷新数据
      await nextTick()
      if (taskAssociationsTabRef.value) {
        try {
          taskAssociationsTabRef.value.refreshRequirements?.()
          taskAssociationsTabRef.value.refreshDefects?.()
        } catch (error) {
          console.error('刷新关联列表失败:', error)
        }
      }
    }
  }
)

// Methods
const handleClose = () => {
  editingContent.value = false
  Object.keys(fieldErrors).forEach(key => delete fieldErrors[key])
  emit('update:visible', false)
  emit('update:modelValue', false)
}
</script>

<style scoped lang="scss">
.task-detail-dialog {
  :deep(.el-dialog) {
    max-height: 90vh;
    display: flex;
    flex-direction: column;
  }

  :deep(.el-dialog__body) {
    padding: 24px;
    flex: 1;
    min-height: 0;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }

  :deep(.el-dialog__header) {
    padding: 20px 24px;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  :deep(.el-dialog__title) {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
  }

  :deep(.el-dialog__footer) {
    padding: 16px 24px;
    border-top: 1px solid #ebeef5;
    flex-shrink: 0;
  }
}

.task-detail {
  display: flex;
  flex-direction: column;
  gap: 24px;
  height: 100%;
  min-height: 0;
}

.detail-header {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 16px;
}

.header-top {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.detail-id {
  font-size: 13px;
  color: #909399;
  background: #f4f6fa;
  padding: 4px 10px;
  border-radius: 4px;
  font-weight: 500;
}

.status-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.title-section {
  margin-bottom: 8px;
}

.field-label {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #606266;

  .required {
    color: #f56c6c;
  }
}

.title-input {
  width: 100%;
}

.field-error {
  :deep(.el-input__wrapper) {
    border-color: #f56c6c;
  }
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
}

.field-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

.select-prefix-avatar {
  margin-right: 8px;
  flex-shrink: 0;
}

.header-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  font-size: 13px;
  color: #606266;
  align-items: center;
  
  .meta-user-item {
    display: flex;
    align-items: center;
    gap: 6px;
    
    .meta-label {
      white-space: nowrap;
    }
  }
  line-height: 1.8;

  span {
    white-space: nowrap;
  }

  .project-info,
  .version-info {
    color: #409eff;
  }
}

.detail-body {
  display: flex;
  gap: 24px;
  flex: 1;
  min-height: 0;
  overflow: hidden;
  align-items: flex-start;
}

.primary-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-height: 0;
  overflow: hidden;
}

.side-column {
  width: 400px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  padding: 24px;
  position: sticky;
  top: 0;
  align-self: flex-start;
  gap: 16px;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }
}

.section-card {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 12px;
  padding: 20px 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  box-shadow: 0 4px 12px rgba(31, 56, 88, 0.05);
}

.content-section {
  padding: 0;
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

.content-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  border-bottom: 1px solid #ebeef5;
}

.content-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.content-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.content-scrollable {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  min-height: 0;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;

    &:hover {
      background: #a8a8a8;
    }
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }
}

.content-editor {
  width: 100%;
}

.content-display {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.content-display-item {
  display: flex;
  flex-direction: column;
  gap: 12px;

  &:not(:last-child) {
    padding-bottom: 24px;
    border-bottom: 1px solid #ebeef5;
  }
}

.content-display-label {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.content-empty {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  padding: 40px 0;
}

.tabs-card {
  padding: 0;
  overflow: hidden;

  :deep(.el-tabs__header) {
    margin: 0;
    padding: 0 24px;
    border-bottom: 1px solid #ebeef5;
  }

  :deep(.el-tabs__content) {
    padding: 24px;
    flex: 1;
    overflow-y: auto;
    min-height: 0;
  }

  :deep(.el-tab-pane) {
    height: 100%;
  }
}

.detail-tabs {
  height: 100%;
  display: flex;
  flex-direction: column;

  :deep(.el-tabs__header) {
    margin: 0;
    padding: 0 24px;
    border-bottom: 1px solid #ebeef5;
  }

  :deep(.el-tabs__content) {
    padding: 24px;
    flex: 1;
    overflow-y: auto;
    min-height: 0;
  }

  :deep(.el-tab-pane) {
    height: 100%;
  }
}

.tab-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 100%;
  overflow-y: auto;
}

.other-section {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.other-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.info-card {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 12px;
  padding: 18px 20px;
  display: flex;
  flex-direction: column;
  gap: 14px;
  box-shadow: 0 4px 12px rgba(31, 56, 88, 0.05);
}

.info-card-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.info-form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-label {
  color: #909399;
  font-size: 13px;
}

.required {
  color: #f56c6c;
  margin-left: 4px;
}

.text-content {
  min-height: 60px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 8px;
  color: #606266;
  line-height: 1.7;
  white-space: pre-wrap;
  word-wrap: break-word;

  &:empty::before {
    content: '暂无内容';
    color: #909399;
  }
}

.other-info {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.other-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }
}

.other-label {
  font-size: 13px;
  color: #909399;
  font-weight: 500;
}

.other-value {
  font-size: 13px;
  color: #606266;
  text-align: right;
}

.user-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

// 响应式设计
@media (max-width: 992px) {
  .detail-body {
    flex-direction: column;
  }

  .side-column {
    width: 100%;
    border-left: none;
    border-top: 1px solid #ebeef5;
    padding-left: 0;
    padding-top: 16px;
  }
}
</style>
